package jk.fox.registry.zookeeper;

import jk.fox.config.registry.zookeeper.ZookeeperConfiguration;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.log4j.Logger;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cuichao
 * @Description: ZookeeperClient
 * @Date: create in 2020/5/17 13:04
 */
public class ZookeeperClient {
    private static Logger logger = Logger.getLogger(ZookeeperClient.class);

    public static final String RPC_ROOT_PATH = "/fox";
    public static final String RPC_NODE_LIST_PATH = "/nodeList";
    public static final String RPC_NODE_CONFIG_PATH = "/config";

    private CuratorFramework client;
    private String zkServers;
    private int maxRetires;
    private int retryIntervalMs;
    private int sessionTimeoutMs;
    private int connectionTimeoutMs;
    private Lock lock = new ReentrantLock();

    public ZookeeperClient(ZookeeperConfiguration config){
        this.zkServers =config.getServerAddress();
        this.maxRetires = config.getMaxRetires();
        this.retryIntervalMs = config.getRetryIntervalMs();
        this.sessionTimeoutMs = config.getSessionTimeoutMs();
        this.connectionTimeoutMs = config.getConnectionTimeoutMs();
    }



    public CuratorFramework get(){
        if(!isStarted()){
            lock.lock();
            try{
                if(!isStarted()){
                    start();
                }
            }finally {
                lock.unlock();
            }

        }
        return this.client;
    }

    private boolean isStarted(){
        return  client != null && client.getState() != CuratorFrameworkState.STOPPED;
    }


    public void start(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(retryIntervalMs, maxRetires);
        this.client = CuratorFrameworkFactory.newClient(zkServers, sessionTimeoutMs, connectionTimeoutMs, retryPolicy);
        client.start();
        logger.debug("Zookeeper client has start");


    }



    public String getServiceNodePath(String node){
        return ZookeeperClient.RPC_ROOT_PATH+"/"+node+ZookeeperClient.RPC_NODE_LIST_PATH;
    }


    public String getServiceConfigPath(String node){
        return ZookeeperClient.RPC_ROOT_PATH+"/"+node+ZookeeperClient.RPC_NODE_CONFIG_PATH;
    }






}
